<template>
  <div class="setting-container">
    <!-- 分配权限的弹层 -->
    <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog" @open="openAssignDialog">
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="permissionData"
        :props="{label: 'name'}"
        :default-expand-all="true"
        :show-checkbox="true"
        :check-strictly="true"
        node-key="id"
      />
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button type="primary" @click="clickAssign">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="clickShowAdd"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="loading" :data="list">
              <el-table-column type="index" :index="indexMethod" label="序号" width="100" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="clickShowAssignDialog(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="showEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRoles(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
              <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                  <el-input v-model="form.description" placeholder="请输入角色描述" />
                </el-form-item>
              </el-form>

              <template #footer>
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="submitBtn">确认</el-button>
              </template>
            </el-dialog>
          </el-tab-pane>

          <!-- 右侧 -->
          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqDeleteRole, reqAddRole, reqGetRoleDetail, reqUpdateRole, reqAssignPerm } from '@/api/setting'
import { reqGetPermissionList } from '@/api/permission'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { listToTreeData } from '@/utils'
export default {
  data() {
    return {
      loading: false,
      showAssignDialog: false,
      permissionData: [], // 存储权限数据
      roleId: '', // 记录正在操作的角色id
      list: [],
      page: 1,
      pagesize: 3,
      total: 0,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: ['blur', 'change'] }
        ]
      },
      companyForm: {}
    }
  },
  // 计算属性，控制标题
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList() // 获取角色列表
    this.getCompanyInfo() // 获取公司信息
  },
  methods: {
    async clickAssign() {
      await reqAssignPerm({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('权限分配成功')
      this.showAssignDialog = false
    },
    async openAssignDialog() {
      this.loading = true
      // 发送请求, 获取权限列表
      const { data } = await reqGetPermissionList()
      this.permissionData = listToTreeData(data, '0')

      const res = await reqGetRoleDetail(this.roleId)
      // console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
      // console.log(this.$refs.tree.setCheckedKeys([res.data.permIds]))
      // console.log(this.permissionData)
      this.loading = false
    },
    // 关闭弹层
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    clickShowAssignDialog(id) {
      this.roleId = id
      this.showAssignDialog = true
    },
    // 获取角色列表
    async getRoleList() {
      this.loading = true
      const { data } = await reqGetRoleList(this.page, this.pagesize)
      // console.log(res)
      this.list = data.rows
      this.total = data.total
      this.loading = false
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 每条页数
      this.pagesize = val
      // 重置当前页为第一页
      this.page = 1
      // 调用方法重新渲染
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    },
    // 序号
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 删除角色
    delRoles(id) {
      this.$confirm('是否删除此角色', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await reqDeleteRole(id)
        this.$message.success('删除角色成功')
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        // 重新获取角色列表
        this.getRoleList()
      }).catch(() => {})
    },
    // 打开弹层
    clickShowAdd() {
      this.showDialog = true
    },
    // 关闭弹层
    closeDialog() {
      this.showDialog = false
      this.form = {
        name: '',
        description: ''
      }
      // 重置数据
      this.$refs.roleForm.resetFields()
    },
    // 新增角色
    submitBtn() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return

        if (this.form.id) {
          // 编辑操作
          await reqUpdateRole(this.form)
        } else {
          // 添加操作
          await reqAddRole(this.form)
        }

        // 添加/编辑 成功提示
        this.$message.success(`${this.form.id ? '编辑' : '新增'}成功`)
        // 关闭弹框
        this.closeDialog()
        // 重新渲染
        this.getRoleList()
      })
    },
    // 编辑
    async showEdit(id) {
      const { data } = await reqGetRoleDetail(id)
      this.form = data
      this.showDialog = true
    },
    // 获取公司信息
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    }

  }
}
</script>

<style>

</style>
